<template>
  <div>
    <toggle-content>
      <el-select v-model="selectSearchType" size="mini" placeholder="请选择">
        <el-option label="学号" value="1"> </el-option>
        <el-option label="姓名" value="2"> </el-option>
      </el-select>
      <el-input
        size="mini"
        v-model="search"
        @change.native="searchStudent"
        style="margin-top: 5px"
        :placeholder="
          selectSearchType
            ? `请根据${selectSearchType === '1' ? '学号' : '姓名'}搜索`
            : '请选择搜索类型'
        "
      >
      </el-input>
      <br />
      <br />
      <el-button @click="exportExcel"> 导出 Excel </el-button>
      <el-table
        ref="table"
        text="加载中..."
        v-loading="tableData.length <= 0"
        height="700"
        :data="tableData"
        style="width: 100%"
      >
        <el-table-column label="ID" prop="_id"> </el-table-column>
        <el-table-column label="学号" prop="studentNo"> </el-table-column>
        <el-table-column label="姓名" prop="studentName"> </el-table-column>
        <el-table-column label="生日" prop="studentBirthday"> </el-table-column>
        <el-table-column label="父母姓名" prop="studentParentName">
        </el-table-column>
        <el-table-column label="电话" prop="studentParentPhone">
        </el-table-column>
        <el-table-column label="地址" prop="studentNowAddress">
        </el-table-column>
        <el-table-column align="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="danger"
              v-if="userInfo.role === 'dean' || userInfo.role === 'admin'"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-row style="margin-top: 10px">
        <el-col>
          <el-pagination
            @current-change="pageCurrentChange"
            @prev-click="pagePrevClick"
            @next-click="pageNextClick"
            :small="small"
            :page-size="12"
            :total="count"
            background
            layout="prev, pager, next"
          >
          </el-pagination>
        </el-col>
      </el-row>
    </toggle-content>
  </div>
</template>

<script>
import { isMobile } from "@/util/util";

import { useGetStudents, useDeleteStudent } from "@/hooks/student";
import { useGetStudentCount } from "@/hooks/controlBoard";

import { mapState } from "vuex";

export default {
  name: "Student",
  inject: ["app"],
  data() {
    return {
      small: false,
      tableData: [],
      count: 0,
      search: "",
      selectSearchType: "",
      pageSize: 12,
      sheet: null,
    };
  },
  mounted() {
    if (this.$route.query.searchContent) {
      this.search = decodeURIComponent(this.$route.query.searchContent);
      this.selectSearchType = "2";
    } else {
      (async () => {
        this.count = (await useGetStudentCount()).count;
        this.tableData = (await useGetStudents()).data?.studens.map((c) => {
          c.studentBirthday = new Date(c.studentBirthday).toLocaleDateString();
          return c;
        });
      })();
    }
    this.small = isMobile();
  },
  computed: {
    ...mapState("user", ["userInfo"]),
  },
  watch: {
    async selectSearchType(selectType) {
      if (!this.search) {
        return this.$message.error("请选择搜索内容");
      }
      this.commonGetTableData();
    },
    $route: {
      handler(route) {
        if (route.name === "student") {
          (async () => {
            this.count = (await useGetStudentCount()).count;
            this.tableData = (await useGetStudents()).data?.studens.map((c) => {
              c.studentBirthday = new Date(
                c.studentBirthday
              ).toLocaleDateString();
              return c;
            });
          })();
        }
      },
      deep: true,
    },
  },
  methods: {
    async searchStudent() {
      if (!this.selectSearchType) {
        return this.$message.error("请选择类型");
      }
      this.commonGetTableData();
    },
    handleEdit(index, row) {
      this.$router.push("/student/edit");
    },
    handleDelete(index, row) {
      this.$confirm("此操作将永久删除该学生, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { _id } = row;
          const resInfo = await useDeleteStudent(_id);
          // 此处可以做更详细的判断 我就省略了......
          this.$message.success("删除成功!");
          this.commonGetTableData();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async commonGetTableData(currentPage) {
      const resInfo = await useGetStudents(
        this.selectSearchType ? this.selectSearchType : null,
        this.search ? this.search : null,
        currentPage ? currentPage : null
      );
      if (resInfo.code === 201 && resInfo.message === "success") {
        this.tableData = resInfo.data.studens.map((c) => {
          c.studentBirthday = new Date(c.studentBirthday).toLocaleDateString();
          return c;
        });
      } else {
        this.$message.error(resInfo.message);
      }
    },
    async pageCurrentChange(currentPage) {
      this.commonGetTableData(currentPage);
      this.app.$refs["main"].$el.scrollTo(0, 0);
    },
    async pagePrevClick(currentPage) {
      this.commonGetTableData(currentPage);
    },
    async pageNextClick(currentPage) {
      this.commonGetTableData(currentPage);
    },
  },
};
</script>
